import { login, getMenuForUser } from '@/api/user.js'
import { FormMenuTORouter, FromMenuToRouter } from '@/router/index.js'

//   获取本地用户的菜单
const menu = localStorage.getItem('menu') ? JSON.parse(localStorage.getItem('menu')) : null
const organizationList = localStorage.getItem('organizationList')
	? JSON.parse(localStorage.getItem('organizationList'))
	: []
const member = localStorage.getItem('member')
	? JSON.parse(localStorage.getItem('member'))
	: []
const tokenList = localStorage.getItem('tokenList') ? JSON.parse(localStorage.getItem('tokenList')) : {}
menu && FormMenuTORouter(menu)
const state = {
	logeed: false,
	member: member,
	organizationList: organizationList,
	tokenList: tokenList,
	menu: menu,
}

const mutations = {
	SET_LOGEED: state => {
		state.logeed = true
	},
	SET_TOKEN: (state, payload) => {
		state.tokenList = payload
		localStorage.setItem('tokenList', JSON.stringify(payload))
	},
	SET_MERBER: (state, payload) => {
		state.member = payload
		localStorage.setItem('member', JSON.stringify(payload))
	},
	SET_ORGAN: (state, payload) => {
		state.organizationList = payload
		localStorage.setItem('organizationList', JSON.stringify(payload))
	},
	SET_MENU: (state, payload) => {
		state.menu = payload
		localStorage.setItem('menu', JSON.stringify(payload))
	},
}

const actions = {
	login({ commit }, userInfo) {
		return new Promise((resolve, reject) => {
			login(userInfo).then(response => {
				// 切换登录状态
				commit('SET_LOGEED')
				// 保存token信息
				commit('SET_TOKEN', response.data.tokenList)
				// 保存member信息
				commit('SET_MERBER', response.data.member)
				// 保存organizationList信息
				commit('SET_ORGAN', response.data.organizationList)
				resolve(response)
			})
		})
	},
	getMenu({ commit }) {
		return new Promise((resolve, reject) => {
			getMenuForUser()
				.then(res => {
					commit('SET_MENU', res.data)
					// 生成路由表
					FormMenuTORouter(res.data)
					// 路由跳转
					resolve(res)
				})
				.catch(() => {
					reject()
				})
		})
	},
}
export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
